package com.miracle9.game.thread;

import com.miracle9.game.bean.GameTypeSession;
import com.miracle9.game.dao.SystemConfigServiceDao;
import com.miracle9.game.dao.UserAwardServiceDao;
import com.miracle9.game.dao.UserServiceDao;
import com.miracle9.game.dao.UserWarningServiceDao;
import com.miracle9.game.entity.AdminLog;
import com.miracle9.game.entity.SystemConfig;
import com.miracle9.game.entity.User;
import com.miracle9.game.entity.UserAward;
import com.miracle9.game.server.message.AmfMessageSend;
import com.miracle9.game.server.message.MessageSend;
import com.miracle9.game.server.message.StorageMethodEntity;
import com.miracle9.game.util.GameParameterAssist;
import com.miracle9.game.util.MyUtil;
import com.miracle9.game.util.SessionUtils;
import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service("userRebateTask")
public class UserRebateTask {
    private Logger logger = Logger.getLogger(UnLockBlackListIPThread.class);
    @Autowired
    private UserServiceDao userServiceDao;
    @Autowired
    private SystemConfigServiceDao systemConfigServiceDao;

    @Autowired
    private UserWarningServiceDao userWarningServiceDao;

    @Autowired
    private com.miracle9.game.dao.AdminLogServiceDao adminLogServiceDao;

    @Autowired
    private UserAwardServiceDao userAwardServiceDao;

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    @PostConstruct
    public void myThreadStart() {
        start();
    }


    public void start() {
        // 获取当前时间
        long currentTime = System.currentTimeMillis();
        // 计算当天0点一分的时间
        long targetTime = currentTime / (24 * 60 * 60 * 1000) * (24 * 60 * 60 * 1000) + 60 * 1000;
        // 计算第一次执行任务的延迟时间
        long initialDelay = targetTime - currentTime;
        // 使用 scheduleAtFixedRate 方法执行任务
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    SystemConfig config = systemConfigServiceDao.getSystemConfig();
                    if(config.getProxyMode() != 1){
                        logger.info("非全民代理模式,不计算返佣");
                        return;
                    }
                    Date date = new Date();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.DAY_OF_MONTH, -1);
                    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
                    String s =  dateFormat.format(calendar.getTime());
                    String startDate =s + " 00:00:00";
                    String endDate = s + " 23:59:59";;
                    String hql2 = "select ifnull(sum(ya_gold),0) ,ifnull(sum(de_gold),0),user_id from user_ten_min_score where  start_time>=? and end_time<=? group by user_id ";
                    List<Object[]> log = userServiceDao.returnList_3(hql2, startDate, endDate);

                    for (Object[] o2 : log) {
                        long lastYaGold = Long.parseLong(o2[0].toString());
                        long lastDeGold = Long.parseLong(o2[1].toString());
                        int userId = Integer.parseInt(o2[2].toString());
                        long lastTotalGain = lastDeGold - lastYaGold;
                        //向上找三级 返佣
                        if(config.getRebate1() == 0 && config.getRebate2()== 0 && config.getRebate3()== 0 ){
                            break;
                        }
                        User user = userServiceDao.q_CreateSqlFilter("from User where id=?", new Object[]{userId});
                        if(user.getParentId() == 0){
                            //自己是顶级 不需要返佣
                            break;
                        }
                        User tempUser = userServiceDao.q_CreateSqlFilter("from User where id=?", new Object[]{user.getParentId()});
                        if(tempUser.getParentId() != 0){
                            User tempUser2 = userServiceDao.q_CreateSqlFilter("from User where id=?", new Object[]{tempUser.getParentId()});
                            if(tempUser2.getParentId()!=0){
                                User tempUser3 = userServiceDao.q_CreateSqlFilter("from User where id=?", new Object[]{tempUser2.getParentId()});
                                addMoney(config.getRebate1(),tempUser,lastTotalGain);
                                addMoney(config.getRebate2(),tempUser2,lastTotalGain);
                                addMoney(config.getRebate3(),tempUser3,lastTotalGain);
                            }else {
                                addMoney(config.getRebate1(),tempUser,lastTotalGain);
                                addMoney(config.getRebate2(),tempUser2,lastTotalGain);
                            }
                        }else {
                            //直属一级
                            addMoney(config.getRebate1(),tempUser,lastTotalGain);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }, initialDelay, 24 * 60 * 60 * 1000, TimeUnit.MILLISECONDS);

    }

    private void addMoney(int rebate,User tempUser,long lastTotalGain){
        int score = new BigDecimal( rebate).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(lastTotalGain)).intValue();
        if(score ==  0){
            return;
        }
        logger.info("计算返佣 rebate = "+rebate +",userid="+tempUser.getId()+",lastTotalGain="+lastTotalGain+",score="+score);
        userServiceDao.updateGameById2(tempUser.getId(), score, tempUser.getIncome()+score,score);
       /* UserAward ua = new UserAward();
        ua.setUserId(tempUser.getId());
        ua.setUsername(tempUser.getUsername());
        ua.setGold(score);
        ua.setStatus(0);
        ua.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
        ua.setAdmin("系统返佣");
        ua.setAuthority(1);
        userWarningServiceDao.updateGiveInfoByUid(tempUser.getId(), score);
        AdminLog adminLog = new AdminLog("系统返佣", "对会员“" + tempUser.getUsername() + "”进行了“赠送游戏币”操作，赠送了" + score + "游戏币", 0, 1, "The operation of present coins has been operated for the member which ID is " + tempUser.getUsername() + " ,a total of " + score + " coins");
        adminLogServiceDao.addAdminLog(adminLog);
        userAwardServiceDao.save(ua);*/
    }
}
